#include "String.h"

#define _CRT_SECURE_NO_DEPRECATE

#include "ContainerManagement.h"

#include <cstring>
#include <assert.h>

namespace EngineLib {

	unsigned int String::BKDRHash(char *str)
	{
		unsigned int seed = 131; // 31 131 1313 13131 131313 etc..
		unsigned int hash = 0;
		char *s = str;

		while (*s)
		{
			hash = hash * seed + (*s++);
		}

		return (hash & 0x7FFFFFFF);
	}

	unsigned int String::Interning(char *cstr)
	{
		unsigned int code = BKDRHash(cstr);
		char *cur = ContainerManagement::stringMap->Get(code);
		assert(!cur || !strcmp(cstr, cur));
		if (cur)
			return code;
		char *store = (char*)ContainerManagement::stringStack->AllocateLeft(strlen(cstr)+1);
		strcpy(store, cstr);
		ContainerManagement::stringMap->Insert(code, store);
		return code;
	}

	char* String::FromHashCode(unsigned int code)
	{
		return ContainerManagement::stringMap->Get(code);
	}
}